import {login, logout, getInfo, getTaskAndReadNum} from '@/api/login'
import {getToken, setToken, removeToken, clearAllCookie} from '@/utils/auth'
import defAva from '@/assets/images/profile.jpg'
import Conf from '@/utils/conf'
const useUserStore = defineStore(
  'user',
  {
    state: () => ({
      token: getToken(),
      name: '',
      avatar: '',
      roles: [],
      permissions: [],
      taskCount: 0,
      readCount: 0,
    }),
    actions: {
      // 获取待办待阅数量
      async getTaskAndReadCount() {
        if (Conf.UNIFLOW_ENABLED) {
          const res = await getTaskAndReadNum();
          this.taskCount = res?.data?.taskCount;
          this.readCount = res?.data?.readCount;
        }
      },
      // 登录
      async login(userInfo) {
        const username = userInfo.username.trim()
        const password = userInfo.password
        const code = userInfo.code
        const uuid = userInfo.uuid
        const res = await login(username, password, code, uuid);
        setToken(res.token);
        this.token = res.token;
      },
      // 获取用户信息
      async getInfo() {
        const res = await getInfo();
        const user = res.user;
        const avatar = (!user.avatar) ? defAva : Conf.BASE_API_URL + user.avatar;

        if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
          this.roles = res.roles
          this.permissions = res.permissions
        } else {
          this.roles = ['ROLE_DEFAULT']
        }
        this.name = user.userName;
        this.avatar = avatar;
        return res;
      },
      // 退出系统
      async logOut() {
        await logout(this.token);
        this.token = '';
        this.roles = [];
        this.permissions = [];
        removeToken();
        clearAllCookie();
      }
    }
  })

export default useUserStore
